﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using System.Web.Security;

/**
 * 微信签名接口认证
 * 示例
 * WeiXinValid wv = new WeiXinValid("token");
 */
namespace WeiXin
{
    public class WeiXinValid
    {
        private string Token;

        public WeiXinValid(String _token)
        {
            Valid(_token);
        }

        private void Valid(String _token)
        {
            Token = _token;
            string echoStr = System.Web.HttpContext.Current.Request.QueryString["echostr"];
            if (CheckSignature())
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    System.Web.HttpContext.Current.Response.Write(echoStr);
                    System.Web.HttpContext.Current.Response.End();
                    Log.WriteLog(DefaultData.ACTION_TYPE_VALID_SUCCESS);
                    return;
                }
                Log.WriteLog(DefaultData.ACTION_TYPE_VALID_FAIL_TOKEN);
            }
            Log.WriteLog(DefaultData.ACTION_TYPE_VALID_FAIL_URL);
        }

        /// <summary>  
        /// 验证微信签名  
        /// </summary>  
        /// * 将token、timestamp、nonce三个参数进行字典序排序  
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密  
        /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。  
        /// <returns></returns>  
        private bool CheckSignature()
        {
            string signature = System.Web.HttpContext.Current.Request.QueryString["signature"];
            string timestamp = System.Web.HttpContext.Current.Request.QueryString["timestamp"];
            string nonce = System.Web.HttpContext.Current.Request.QueryString["nonce"];
            string[] ArrTmp = { Token, timestamp, nonce };
            Array.Sort(ArrTmp);     //字典排序  
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
